<?php
	require_once('../ethereum/dbc.php');

    class Ctc{
        public function index($param,$db){
            $sql = 'SELECT id,uname,phone FROM ld_user_info WHERE id = '.$param['uid'];
            return $db->select_one($sql);
        }

        public function selllist($param,$db){
        	$sql = 'SELECT mum,price,mum*price as total FROM ld_trade where type = 2 AND status =0 AND mum >0 ORDER BY price asc,addtime desc LIMIT 10';
        	return $db->select_all($sql);
        }

        public function buylist($param,$db){
        	$sql = 'SELECT mum,price,mum*price as total FROM ld_trade where type = 1 AND status =0 AND mum > 0  ORDER BY price desc,addtime desc LIMIT 10';
        	return $db->select_all($sql);
        }

        public function min_price($param,$db){
        	$sql = 'SELECT price FROM ld_trade_log ORDER BY price asc LIMIT 1';
        	return $db->select_one($sql);
        }

        public function max_price($param,$db){
        	$sql = 'SELECT price FROM ld_trade_log ORDER BY price desc LIMIT 1';
        	return $db->select_one($sql);
        }

        public function buy_one($param,$db){
        	$sql = 'SELECT price FROM ld_trade where type = 1 AND status =0 AND mum >0  ORDER BY price desc,addtime desc LIMIT 1';
        	return $db->select_one($sql);
        }

        public function sell_one($param,$db){
        	$sql = 'SELECT price FROM ld_trade where type = 2 AND status =0 AND mum >0  ORDER BY price asc,addtime desc LIMIT 1';
        	return $db->select_one($sql);
        }

        public function total_num($param,$db){
        	$sql = 'SELECT SUM(num) as total FROM ld_trade_log';
        	return $db->select_one($sql);
        }

        public function out_order($param,$db){
            $buy['status'] = 3;
            $db->update($buy, 'ld_trade', 'id = '.$param['id']);
            $sql = 'SELECT * FROM ld_trade WHERE id ='.$param['ids'];
            $data = $db->select_one($sql);
            $sell['status'] = 0;
            $sell['pid'] = 0;
            $sell['dum'] = 0;
            $sell['mum'] = $data['mum'] + $data['dum'];
            $db->update($sell, 'ld_trade', 'id = '.$param['ids']);
            return true;
        }

        public function entrust_cnt($param,$db){
            $sql = 'SELECT id,num,(num - mum - dum) AS remain,dum,price,status,(CASE WHEN status = 0 THEN "撤销" WHEN status = 1 THEN "交易中" WHEN status = 2 THEN "已成交" WHEN status =3 THEN "已撤销" ELSE "其它" END) AS status_name,type,(CASE WHEN type = 1 THEN "买入" WHEN type=2 THEN "卖出" ELSE "其它" END) AS types,money,from_unixtime(addtime) AS addtime FROM ld_trade where userid = '.$param['userid'].' AND status = 0 AND dum = 0  ORDER BY status asc,type asc,id desc';
            return $db->select_all($sql);
        }

        public function record_cnt($param,$db){
            $sql = 'SELECT num,price,num*price AS total,from_unixtime(addtime) AS datetimes,addtime,type,(CASE WHEN type=1 THEN "买入" WHEN type = 2 THEN "卖出" ELSE "其它" END) AS types FROM ld_trade_log ORDER BY addtime desc LIMIT 50';
            return $db->select_all($sql);
        }

        //买卖下单
        public function push_order($param,$db){
            //{userid: "8501", type: "1", buy_price: "101.1", buy_number: "1000.0"}
            $sql = 'SELECT id,num,mum,dum,price,img FROM ld_trade where type = 2 AND status =0 AND mum >0  ORDER BY price asc,addtime desc LIMIT 1';
            $data = $db->select_one($sql);
            if(empty($data)){
                //下单
                $add_data['userid'] = $param['userid'];
                $add_data['num'] = $param['buy_number'];
                $add_data['mum'] = $param['buy_number'];
                $add_data['dum'] = 0;
                $add_data['price'] = $param['buy_price'];
                $add_data['money'] = 0;
                $add_data['status'] = 0;
                $add_data['type'] = $param['type'];
                $add_data['img'] = '';
                $add_data['addtime'] = time();
                $db->insert($add_data, 'ld_trade');
                $last = 'SELECT id FROM ld_trade where type = 1 AND status =0 AND userid = '.$param['userid'].'  ORDER BY id desc LIMIT 1';
                $lastdata = $db->select_one($last);
                return array('code'=>200,'msg'=>'下单成功','data'=>['id'=>$lastdata['id'],'ids'=>0]);
            }else{
                if($param['buy_price'] == $data['price']){
                    if($param['buy_number'] <= $data['num']){
                        //下单
                        $add_data['userid'] = $param['userid'];
                        $add_data['num'] = $param['buy_number'];
                        $add_data['mum'] = $param['buy_number'];
                        $add_data['dum'] = 0;
                        $add_data['price'] = $param['buy_price'];
                        $add_data['pid'] = $data['id'];
                        $add_data['money'] = 0;
                        $add_data['status'] = 0;
                        $add_data['type'] = $param['type'];
                        $add_data['img'] = '';
                        $add_data['addtime'] = time();
                        $db->insert($add_data, 'ld_trade');
                        $last = 'SELECT id FROM ld_trade where type = 1 AND status =0 AND userid = '.$param['userid'].'  ORDER BY id desc LIMIT 1';
                        $lastdata = $db->select_one($last);
                        $update_data['pid'] = $lastdata['id'];
                        $update_data['status'] =   1;
                        $update_data['dum'] =   $param['buy_number'];
                        $update_data['mum'] =   $data['mum']-$param['buy_number'];
                        $db->update($update_data, 'ld_trade', 'id = '.$data['id']);
                        return array('code'=>200,'msg'=>'下单成功','data'=>['id'=>$lastdata['id'],'ids'=>$data['id']]);
                    }else{
                        return array('code'=>402,'msg'=>'数量错误','data'=>[]);
                    }
                }elseif($param['buy_price'] < $data['price']){
                    //下单
                    $add_data['userid'] = $param['userid'];
                    $add_data['num'] = $param['buy_number'];
                    $add_data['mum'] = $param['buy_number'];
                    $add_data['dum'] = 0;
                    $add_data['price'] = $param['buy_price'];
                    $add_data['money'] = 0;
                    $add_data['status'] = 0;
                    $add_data['type'] = $param['type'];
                    $add_data['img'] = '';
                    $add_data['addtime'] = time();
                    $db->insert($add_data, 'ld_trade');
                    $last = 'SELECT id FROM ld_trade where type = 1 AND status =0 AND userid = '.$param['userid'].'  ORDER BY id desc LIMIT 1';
                    $lastdata = $db->select_one($last);
                    return array('code'=>200,'msg'=>'下单成功','data'=>['id'=>$lastdata['id'],'ids'=>$data['id']]);
                }else{
                    return array('code'=>401,'msg'=>'价格错误','data'=>[]);
                }
            }
        }

        public function buy_order($param,$db){
            if(!preg_match('/^\d{1,5}\.\d$/', $param['price'])){
                return array('code'=>401,'msg'=>'数据错误','data'=>[]);
            }
            if($param['type']!=1){
                return array('code'=>402,'msg'=>'类型错误','data'=>[]);
            }
            $sql = 'SELECT mum,price,img FROM ld_trade where type = 2 AND status =0 AND mum >0  ORDER BY price asc,addtime desc LIMIT 1';
            $data = $db->select_one($sql);
            if(empty($data)){
                return array('code'=>200,'msg'=>'查询成功','data'=>['number'=>'--','price'=>$param['price']]);
            }else{
                //当前价格大于等于卖一价
                if(floatval($param['price']) >= floatval($data['price'])){
                    return array('code'=>200,'msg'=>'查询成功','data'=>['number'=>$data['mum'],'price'=>floatval($data['price']),'img'=>$data['img']]);
                }else{
                    //当前价格小于卖一价
                    return array('code'=>200,'msg'=>'查询成功','data'=>['number'=>'--','price'=>$param['price'],'img'=>$data['img']]);
                }
            }
        }

        public function my_cexiao($param,$db){
            $sql = 'SELECT * FROM ld_trade WHERE status =0 AND id = '.$param['id'];
            $data = $db->select_one($sql);
            if(empty($data)){
                return array('code'=>400,'msg'=>'未查询到订单','data'=>[]);
            }
            if($data['type'] == 1){
                $update['status'] = 3;
                $db->update($update, 'ld_trade', 'id = '.$param['id']);
                return array('code'=>200,'msg'=>'买单撤销成功','data'=>[]);
            }else{
                $update['status'] = 3;
                $db->update($update, 'ld_trade', 'id = '.$param['id']);
                $sqls = 'SELECT lixi_crash FROM ld_user_account WHERE id = '.$data['userid'];
                $datas = $db->select_one($sqls);
                if(empty($datas)){
                    return array('code'=>400,'msg'=>'未查询到用户','data'=>[]);
                }
                $update_data['lixi_crash'] = $datas['lixi_crash'] + $data['mum'];
                $db->update($update_data, 'ld_user_account', 'id = '.$data['userid']);
                return array('code'=>201,'msg'=>'卖单撤销成功','data'=>[]);
            }
        }

        public function queren_cnt($param,$db){
            $sql = 'SELECT id,num,price,dum,dum*price AS total,from_unixtime(addtime) AS datetimes,addtime,type,(CASE WHEN type=1 THEN "买入" WHEN type = 2 THEN "卖出" ELSE "其它" END) AS types FROM ld_trade where userid = '.$param['userid'].' AND type = 2 AND status =1';
            return $db->select_all($sql);
        }

        public function get_user_vic($param,$db){
            $sql = 'SELECT lixi_crash FROM ld_user_account WHERE id = '.$param['userid'];
            $data = $db->select_one($sql);
            $num = intval($data['lixi_crash']*10)/10;
            return ['num'=>$num];
        }

        public function queren_order($param,$db){
            $sql = 'SELECT * FROM ld_trade where id = '.$param['id'] .' AND status = 1';
            $data = $db->select_one($sql);
            if(empty($data)){
                return array('code'=>400,'msg'=>'数据异常','data'=>[]);
            }
            if(!$data['pid']){
               return array('code'=>401,'msg'=>'匹配的订单异常','data'=>[]); 
            }
            $buysql = 'SELECT * FROM ld_trade where id = '.$data['pid'];
            $buydata = $db->select_one($buysql);
            if(empty($buydata)){
                return array('code'=>402,'msg'=>'未查询到匹配订单','data'=>[]);
            }
            if(floatval($buydata['dum']) != floatval($data['dum'])){
                return array('code'=>402,'msg'=>'订单匹配失败','data'=>[]);
            }
            //买单成交
            $updatebuy['status'] = 2;
            $updatebuy['dum'] = 0;
            $updatebuy['money'] = $buydata['price'] * $buydata['dum'];
            
            //$db->update($updatebuy, 'ld_trade', 'id = '.$data['pid']);
            //成交记录
            $add_log['id'] = 0;
            $add_log['pid'] = $buydata['id'];
            $add_log['uid'] = $buydata['userid'];
            $add_log['num'] = $buydata['dum'];
            $add_log['price'] = $buydata['price'];
            $add_log['addtime'] = time();
            $add_log['type'] = $buydata['type'];
            //return $add_log;
            $db->insert($add_log, 'ld_trade_log');
            //卖单记录
            $update['pid'] = 0;
            $update['dum'] = 0;
            $update['money'] = $data['money'] + $buydata['price'] * $buydata['dum'];
            if($data['mum'] <= 0){
                $update['status'] = 2;
            }else{
                $update['status'] = 0;
            }
            $db->update($update, 'ld_trade', 'id = '.$param['id']);
            //添加用户币
            $sqls = 'SELECT lixi_crash FROM ld_user_account WHERE id = '.$buydata['userid'];
            $datas = $db->select_one($sqls);
            if(empty($datas)){
                return array('code'=>400,'msg'=>'未查询到用户','data'=>[]);
            }
            $update_data['lixi_crash'] = $datas['lixi_crash'] + $buydata['dum'];
            $db->update($update_data, 'ld_user_account', 'id = '.$buydata['userid']);

            return array('code'=> 200 ,'msg'=>'确认成功','data'=>[]);
        }

        public function period($param,$db){
        	$new_time = time();
        	$old_time = $new_time-3600*24;
        	$max_sql = 'SELECT price,addtime FROM ld_trade_log WHERE addtime > '.$old_time.' AND addtime < '.$new_time.' ORDER BY price desc LIMIT 1';
        	$min_sql = 'SELECT price,addtime FROM ld_trade_log WHERE addtime > '.$old_time.' AND addtime < '.$new_time.' ORDER BY price,addtime asc LIMIT 1';
        	$max = $db->select_one($max_sql);
        	$min = $db->select_one($min_sql);
        	if(empty($max)){
        		return array('period'=>'--');
        	}
        	$max_time = intval($max['addtime']);
        	$max_price = floatval($max['price']);
        	$min_time = intval($min['addtime']);
        	$min_price = floatval($min['price']);
	        if($max_time > $min_time){
	        	$period = (string)round((($max_price-$min_price) / $min_price*100),2);
	        	$period = $period."%";
	        }elseif($max_time < $min_time){
	        	$period = (string)round((($max_price-$min_price) / $min_price*100),2);
	        	$period = '- '.$period."%";
	        }else{
	        		$period = '--';
	        }
        	return array('period'=>$period);
        }

        //买上传图片
        public function upload_image($param,$db){
            header('content-type:text/html charset:utf-8');
            $dir_base = "../upload/images/";     //文件上传根目录
            $upload_file_name = 'upload_file0';        //对应index.html FomData中的文件命名
            $filename = $_FILES[$upload_file_name]['name'];
            $gb_filename = iconv('utf-8','gb2312',$filename);    //名字转换成gb2312处理
            //文件不存在才上传
            if(!file_exists($dir_base.$gb_filename)) {
                $isMoved = false;  //默认上传失败
                $MAXIMUM_FILESIZE = 2 * 1024 * 1024;     //文件大小限制    1M = 1 * 1024 * 1024 B;
                $rEFileTypes = "/^\.(jpg|jpeg|gif|png){1}$/i"; 
                if ($_FILES[$upload_file_name]['size'] <= $MAXIMUM_FILESIZE && 
                    preg_match($rEFileTypes, strrchr($gb_filename, '.'))) {
                    $isMoved = @move_uploaded_file ( $_FILES[$upload_file_name]['tmp_name'], $dir_base.$gb_filename);        //上传文件
                }
            }else{
                $isMoved = true;    //已存在文件设置为上传成功
            }

            $file_path = 'http://trunk.olnote.com/upload/images/'.$gb_filename;
            $sql = 'SELECT id,mum FROM ld_trade where type = 1 AND status =0 ORDER BY id desc,addtime desc LIMIT 1';
            $trade = $db->select_one($sql);
            $update_data['img'] =   $file_path;
            $update_data['mum'] =   0;
            $update_data['dum'] =   $trade['mum'];
            $db->update($update_data, 'ld_trade', 'id = '.$trade['id']);

            return ['code'=>200,'msg'=>'下单成功','data'=>['path'=>"{$file_path}"]];
        }

                //卖上传图片
        public function upload_image1($param,$db){
            $sql = 'SELECT lixi_crash FROM ld_user_account WHERE id = '.$param['userid'];
            $data = $db->select_one($sql);
            //$num = intval($data['lixi_crash']*10)/10;
            if(empty($data)){
                return array('code'=>400,'msg'=>'缺少必要参数','data'=>[]);
            }
            $num = intval($data['lixi_crash']*10)/10;
            if($param['sell_number'] > floatval($num)){
                return array('code'=>401,'msg'=>'数量错误','data'=>[]);
            }
            if($param['type'] != 2){
                return array('code'=>402,'msg'=>'类型错误','data'=>[]);
            }
            header('content-type:text/html charset:utf-8');
            $dir_base = "../upload/images/";     //文件上传根目录
            $upload_file_name = 'upload_file0';        //对应index.html FomData中的文件命名
            $filename = $_FILES[$upload_file_name]['name'];
            $gb_filename = iconv('utf-8','gb2312',$filename);    //名字转换成gb2312处理
            //文件不存在才上传
            if(!file_exists($dir_base.$gb_filename)) {
                $isMoved = false;  //默认上传失败
                $MAXIMUM_FILESIZE = 2 * 1024 * 1024;     //文件大小限制    1M = 1 * 1024 * 1024 B;
                $rEFileTypes = "/^\.(jpg|jpeg|gif|png){1}$/i"; 
                if ($_FILES[$upload_file_name]['size'] <= $MAXIMUM_FILESIZE && 
                    preg_match($rEFileTypes, strrchr($gb_filename, '.'))) {
                    $isMoved = @move_uploaded_file ( $_FILES[$upload_file_name]['tmp_name'], $dir_base.$gb_filename);        //上传文件
                }
            }else{
                $isMoved = true;    //已存在文件设置为上传成功
            }

            $file_path = 'http://trunk.olnote.com/upload/images/'.$gb_filename;
             //下单
            $add_data['userid'] = $param['userid'];
            $add_data['num'] = $param['sell_number'];
            $add_data['mum'] = $param['sell_number'];
            $add_data['dum'] = 0;
            $add_data['price'] = $param['sell_price'];
            $add_data['pid'] = $data['id'];
            $add_data['money'] = 0;
            $add_data['status'] = 0;
            $add_data['type'] = $param['type'];
            $add_data['img'] = $file_path;
            $add_data['addtime'] = time();
            $db->insert($add_data, 'ld_trade');
            $update_data['lixi_crash'] = $data['lixi_crash'] - $param['sell_number'];
            $db->update($update_data, 'ld_user_account', 'id = '.$param['userid']);
            return array('code'=>200,'msg'=>'下单成功','data'=>[]);
        }
    }

    $ctc = new Ctc();
    $method = $_GET['method'];
    $param = $_POST;
    require ('../common.inc.php');
    $db =  new Dbc($GLOBALARR['dbhost'], $GLOBALARR['dbuser'],$GLOBALARR['dbpwd'], 'utf8', $GLOBALARR['dbname']);
    switch ($method) {
    	case 'index':
    		$return = $ctc->index($param,$db);
    		break;
    	case 'selllist':
    		$return = $ctc->selllist($param,$db);
    		break;
    	case 'buylist':
    		$return = $ctc->buylist($param,$db);
    		break;
    	case 'min_price':
    		$return = $ctc->min_price($param,$db);
    		break;
    	case 'max_price':
    		$return = $ctc->max_price($param,$db);
    		break;
    	case 'buy_one':
    		$return = $ctc->buy_one($param,$db);
    		break;
    	case 'sell_one':
    		$return = $ctc->sell_one($param,$db);
    		break;
    	case 'total_num':
    		$return = $ctc->total_num($param,$db);
    		break;
        case 'period':
            $return = $ctc->period($param,$db);
            break;
        case 'entrust_cnt':
            $return = $ctc->entrust_cnt($param,$db);
            break;
        case 'record_cnt':
            $return = $ctc->record_cnt($param,$db);
            break;
        case 'buy_order':
            $return = $ctc->buy_order($param,$db);
            break;
        case 'push_order':
    		$return = $ctc->push_order($param,$db);
    		break;
        case 'upload_image':
            $return = $ctc->upload_image($param,$db);
            break;
       case 'queren_cnt':
            $return = $ctc->queren_cnt($param,$db);
            break;
       case 'queren_order':
            $return = $ctc->queren_order($param,$db);
            break;
       case 'out_order':
            $return = $ctc->out_order($param,$db);
            break;
        case 'my_cexiao':
            $return = $ctc -> my_cexiao($param,$db);
            break;
        case 'get_user_vic':
            $return = $ctc -> get_user_vic($param,$db);
            break;
        case 'upload_image1':
            $param = [];
            $param['sell_number'] = $_GET['sell_number'];
            $param['sell_price'] = $_GET['sell_price'];
            $param['userid'] = $_GET['userid'];
            $param['type'] = $_GET['type'];
            $return = $ctc -> upload_image1($param,$db);
            break;
    	default:
    		$return = array('code'=>400,'msg'=>'未定义方法',data=>[]);
    		break;
    }
    die(json_encode($return));
